package com.jerry.activeMq.impl;

import com.jerry.activeMq.JerryCustomer;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by jerry on 2016/12/17.
 */
public class JerryCustomerImpl implements JerryCustomer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;

    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;

    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    //factor
    ConnectionFactory connectionFactory;

    //connection
    Connection connection;

    //session
    Session session;

    ThreadLocal<MessageConsumer> consumerThreadLocal = new ThreadLocal<MessageConsumer>();

    @Override
    public void init() {
        connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
        try {
            connection = connectionFactory.createConnection();

            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getMessage(String desName) {
        try {
            Queue queue = session.createQueue(desName);

            MessageConsumer consumer = null;
//            MessageConsumer consumer =  session.createConsumer(queue);

            if (consumerThreadLocal.get() != null) {
                consumer = consumerThreadLocal.get();
            } else {
                consumer = session.createConsumer(queue);
                consumerThreadLocal.set(consumer);
            }
            while (true) {
                TextMessage message = (TextMessage) consumer.receive();

                if (message != null) {
                    System.out.println(Thread.currentThread().getName() + "custom:我消费一条消息,消息内容是：" + message.getText());
                    message.acknowledge();
                } else {
                    break;
                }
            }

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
